<?php

/*
 * Edit by shengxin
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */

namespace api\mall\controller;

use think\App;
use think\facade\Db;
use api\portal\model\UserModel;
use api\user\model\UserBalanceLogModel;
use cmf\controller\RestBaseController;
/**
 * Description of SyncController
 *
 * @author PC
 */
class SyncController extends RestBaseController{
    
    public function __construct(App $app = null) {
        $this->app     = $app ?: app();
        $this->request = $this->app->request;
        $this->check_sign();
    }
    
    private function check_sign(){
        $sign = $this->request->header('sign');
        if(empty($sign)){
            throw new \think\exception\HttpException(403,'Forbidden');
        }
        $data = $this->request->post();
        if(empty($data['time'])){
            $this->error('缺少参数:time');
        }
        $now = time();
        $time = $data['time'];
        if(abs($now - $time)>15){
            $this->error('超时');
        }
        ksort($data,SORT_STRING);
        $str = '';
        foreach ($data as $key => $value) {
            $str .= $key . '=' . $value . '&';
        }
        $secret = config('mall.secret');
        // 去除最后一个"&"符号
        $str = $str.$secret;

        // 计算MD5值
        $md5 = md5($str);
        if($md5==$sign){
            return true;
        }
//        $this->error('签名错误:'.$str.' => '.$md5);
        throw new \think\exception\HttpException(413,'Forbidden');
    }
    
//    public function test_code(){
//        $uid = 12;
//        Db::name('wallet_code')->where('id', $uid)->delete();   
//        $code = cmf_random_string(10);
//        $data = ['id'=>$uid,'code'=>$code,'count'=>1,'send_time'=>time(),'expire_time'=>time()+3600];
//        Db::name('wallet_code')->insert($data);
//        $userModel = new UserModel();
//        $userModel->where('id', $uid)->update(['wallet'=>null]);
//        $this->success('ok',['code'=>$code]);
//    }

    public function bindWallet()
    {
        $data = $this->request->post();
        $result = '内部错误';
        do {
            if (empty($data['code'])) {
                $result = '口令不能为空';
                break;
            }
            if (empty($data['wallet'])) {
                $result = '钱包地址不能为空';
                break;
            }
           
                        
            $userModel = new UserModel();
            $exsitUser = $userModel->where('wallet', $data['wallet'])->find();
            if (!empty($exsitUser)) {
                $result = '钱包地址已经绑定了！';
                break;
            }
            $code = $data['code'];
            $findWalletCode = Db::name('wallet_code')->where('code', $code)->find();
            if (empty($findWalletCode)) {
                $result = '口令无效！';
                break;
            }
            $now = time();
            if ($findWalletCode['expire_time'] < $now) {
                $result = "口令已经过期,请先获取!";
                break;
            }
            $uid = $findWalletCode['id'];
            
            Db::name('wallet_code')->where('id', $uid)->delete();            
            
            $bindUser = $userModel->where('id', $findWalletCode['id'])->find();
            $update = [];
            $update['wallet'] = $data['wallet'];
            if(empty($bindUser['user_url'])){
                $bindUser['user_url'] = $update['user_url'] = substr(md5('wallet2uid'.$data['wallet'].$uid),0,20);
            }
            $userModel->where('id', $uid)->update($update);
            $ret = [];
            $ret['wallet'] = $data['wallet'];
            $ret['user_id'] = $bindUser['user_url'];
            $ret['user_nickname'] = $bindUser['user_nickname'];
            $ret['score'] = $bindUser['score'];            
            $ret['avatar'] = cmf_get_image_url($bindUser['avatar']);            
            $this->success('ok', $ret);
        } while (false);
        $this->error($result);
    }

    /**
     * 同步用户星链石
     * @OA\Post(
     *     tags={"mall-user"},
     *     path="/mall/user/syncScore",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="order_id", type="string", example="SYN662024041193991111"),
     *             @OA\Property(property="wallet", type="string", example="钱包地址"),
     *             @OA\Property(property="score", type="number", example=">0增加 <0减少"),
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function syncScore()
    {
        $data = $this->request->post();
        $result = '内部错误';
        do {
                     
            if (empty($data['wallet'])) {
                $result = '钱包地址不能为空';
                break;
            }
            if (!isset($data['score'])) {
                $result = '金额不能为空';
                break;
            }
            if (!isset($data['order_id'])) {
                $result = '订单号不能为空';
                break;
            }
            $order_id = $data['order_id'];
            $balanceModel = new UserBalanceLogModel();
            $order = $balanceModel->where('order_id',$order_id)->find();
            if($order){
                $result = '已同步';
                break;
            }
            
            $userModel = new UserModel();
            $syncUser = $userModel->where('wallet', $data['wallet'])->find();
            if (empty($syncUser)) {
                $result = '钱包不存在！';
                break;
            }
            $uid  = $syncUser['id'];
            $score = $data['score'];

            if ($score > 0) {
                $userModel->addScorePure($uid, $score, '钱包充值', 'charge');
            }
            else {
                if ($syncUser['score'] < abs($score)) {
                    $result = '余额不足';
                    break;
                }
                $userModel->addScorePure($uid, $score, '钱包提现', 'withdrawal');
            }
            
            $log = [
                'user_id'=>$uid,
                'create_time'=> time(),
                'change'=>$score,
                'balance'=>$syncUser['score']+$score+$syncUser['coin'],
                'description'=>'来自钱包的操作',
                'order_id'=>$order_id,
            ];
            $balanceModel->insert($log);
            
            $ret = [];
            $ret['wallet'] = $syncUser['wallet'];
            $ret['user_nickname'] = $syncUser['user_nickname'];
            $ret['score'] = $syncUser['score']+$score;  
            $this->success('ok', $ret);
        } while (false);
        $this->error($result);
    }
    
    public function queryScore(){
        $data = $this->request->post();
        $result = '内部错误';
        do {
                     
            if (empty($data['wallet'])) {
                $result = '钱包地址不能为空';
                break;
            }
                        
            $userModel = new UserModel();
            $syncUser = $userModel->where('wallet', $data['wallet'])->find();
            if (empty($syncUser)) {
                $result = '钱包不存在！';
                break;
            }
            $ret = [];
            $ret['wallet'] = $syncUser['wallet'];
            $ret['user_nickname'] = $syncUser['user_nickname'];
            $ret['score'] = $syncUser['score'];  
            $this->success('ok', $ret);
        } while (false);
        $this->error($result);
    }
}
